const { think } = require('thinkjs');
const Base = require('./base.js');

module.exports = class extends Base {
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 10;
    const type = this.get('type');
    const query = {
      user_id: this.getLoginUserId()
    };
    if (type !== '0') {
      query.status = type;
    }

    const data = await this.model('notice').order(['id DESC']).where(query).page(page, size).countSelect();

    return this.success(data);
  }

  async noticeReadAction() {
    if (this.get('id')) {
      await this.model('notice').where({ id: this.get('id') }).update({
        read: 1
      });
      const unread = await this.model('notice').where({user_id: this.getLoginUserId(), read: 0}).count();
      const read = await this.model('notice').where({user_id: this.getLoginUserId(), read: 1}).count();
      const count = await this.model('notice').where({user_id: this.getLoginUserId()}).count();
      return this.success({count: count, read: read, unread: unread});
    } else {
      const n = await this.model('notice').where({ user_id: this.getLoginUserId(), read: 0 }).find();
      if (think.isEmpty(n)) {
        return this.fail(408);
      } else {
        await this.model('notice').where({ user_id: this.getLoginUserId() }).update({
          read: 1
        });
        return this.success();
      }
    }
  }
};
